package cn.pli.femedia.MPEG;

import android.media.MediaCodec;
import android.media.MediaExtractor;

import java.nio.ByteBuffer;

import cn.pli.femedia.VideoEncoderCore;
/**
 * Created by foxy on 2017/5/25.
 * 向文件中写入音频数据的线程
 */
public class WriteVoiceTask implements Runnable{
        MediaExtractor extractor;
        int voiceindex;
        int audioMaxInputSize;
        boolean isWritedVoice;
    private TrackIndex trackIndexVioce;
    private FeMuxer mMuxer;

        /**
         * 写入音频方法的构造函数
         * @param extractor     mediaextractor   通过视频文件可得
         * @param voiceindex        文件中的音轨
         * @param audioMaxInputSize 文件中的最大帧大小，通过mediaformat可得
         */

        public WriteVoiceTask(MediaExtractor extractor, int voiceindex, int audioMaxInputSize,FeMuxer mMuxer,TrackIndex trackIndexVioce) {
            this.extractor = extractor;
            this.voiceindex = voiceindex;
            this.audioMaxInputSize = audioMaxInputSize;
            this.isWritedVoice = false;
            this.mMuxer=mMuxer;
            this.trackIndexVioce=trackIndexVioce;
        }

        @Override
        public void run() {
            this.addVideoStream(extractor);
        }

        private  void addVideoStream(MediaExtractor extractor) {
            extractor.selectTrack(voiceindex);
            MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
            ByteBuffer inputBuf = ByteBuffer.allocate(audioMaxInputSize);
            int outputChunk=0;
            while (!isWritedVoice) {
                outputChunk++;
                int sampleSize = extractor.readSampleData(inputBuf, 0);
                if (sampleSize < 0) {
                    isWritedVoice = true;
                    mMuxer.closed(trackIndexVioce);
                }else {
                    info.offset = 0;
                    info.size = sampleSize;
                    info.flags = MediaCodec.BUFFER_FLAG_SYNC_FRAME;
                    info.presentationTimeUs = extractor.getSampleTime();
                    mMuxer.writeSampleData(trackIndexVioce, inputBuf, info);
                    extractor.advance();
                }
            }
        }

}
